package com.woniuxy.boot.bankcard.controller;

import com.woniuxy.boot.bankcard.bean.Bankcard;
import com.woniuxy.boot.bankcard.exception.BalanceIsNotAmpleException;
import com.woniuxy.boot.bankcard.exception.BankcardIsNullException;
import com.woniuxy.boot.bankcard.exception.WrongPasswordException;
import com.woniuxy.boot.bankcard.service.BankcardService;
import com.woniuxy.boot.common.dto.OrderPayDTO;
import com.woniuxy.boot.common.pojo.ResponseResult;
import com.woniuxy.boot.common.util.JwtUtil;
import com.woniuxy.boot.common.vo.BankcardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("app/bankcard")
public class BankcardController {
    @Autowired
    private BankcardService bankcardService;

    /**
     * 用户绑定银行卡接口
     **/
    @PostMapping("bindBankcard")
    public ResponseResult<Void> bindBankcard(@RequestHeader("token") String token, @RequestBody Bankcard bankcard) {
        bankcard.setUserId(JwtUtil.parseJwt(token));
        bankcardService.bindBankcard(bankcard);
        return ResponseResult.SUCCESS;
    }

    /**
     * 用户查询个人银行卡接口
     **/
    @GetMapping("getAllBankcardById")
    public ResponseResult<List<BankcardVO>> getAllBankcardById(@RequestHeader("token") String token) {
        return new ResponseResult<>(bankcardService.getAllBankcardById(JwtUtil.parseJwt(token)));
    }

    /**
     * 支付订单接口
     **/
    @PostMapping("payOrder")
    public ResponseResult<Void> payOrder(@RequestBody OrderPayDTO orderPayDTO) {
        bankcardService.payOrder(orderPayDTO);
        return ResponseResult.SUCCESS;
    }

    /**
     *Bankcard统一异常处理
     **/
    @ExceptionHandler
    public ResponseResult<Void> exceptionHandler(Exception e) {
        if (e instanceof BalanceIsNotAmpleException) {
            return new ResponseResult<>(761, "余额不足异常,支付失败");
        }  else if(e instanceof WrongPasswordException){
            return new ResponseResult<>(762, "银行卡密码输入错误异常,支付失败");
        }else if(e instanceof BankcardIsNullException){
            return new ResponseResult<>(763, "银行卡不存在,支付失败");
        }
        else {
            return new ResponseResult<>(900, "未知异常");
        }
    }

}
